#!/usr/bin/env python
# -- coding: utf-8 --
# @Time : 2023/1/19 15:32
# @Coder: Pithon
# @IDE : PyCharm
# @WEB : http://pithon.top
# ==============================
import calendar
import bs4


def insert_js(industry, year, month, play_interval):
    # html文件地址
    html_path = f'./charts/{industry}/rank_bar_{year}{month}.html'
    # canvas一次循环时长，由当月天数和轮播速度共同决定
    time_out = calendar.monthrange(year, month)[1] * play_interval
    # 导出的视频的文件名
    video_name = f'{industry}_rank_bar_{year}{month}.webm'
    # 操作html，添加video节点和录屏js
    s = bs4.BeautifulSoup(open(html_path), 'lxml')
    s.html.body.div.insert_after(s.new_tag(name='video'))
    s.html.body.video['id'] = "videoContainer"
    s.html.body.video['controls'] = "controls"
    s.html.body.video['style'] = "height:540px;width:960px"

    s.html.body.script.insert_after(s.new_tag(name='script'))
    js = s.findAll('script')[2]
    js_str = """
            const canvas = document.querySelector('canvas');
        const stream = canvas.captureStream(30);
        const recorder = new MediaRecorder(stream, { mimeType: 'video/webm' });
        const data = [];
        recorder.ondataavailable = function (event) {
        if (event.data && event.data.size) {
        data.push(event.data);
            }
        };
        recorder.onstop = () => {
        const url = URL.createObjectURL(new Blob(data, { type: 'video/webm' }));
        document.querySelector("#videoContainer").style.display = "block";
        document.querySelector("video").src = url;

        var element = document.createElement('a');
        element.setAttribute('href', url);
        element.setAttribute('download', '%s');
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
        };
        recorder.start();
        setTimeout(() => {
        recorder.stop();
        },%d);
    """ % (video_name, time_out)
    js.append(s.new_string(js_str))
    with open(html_path, 'w', encoding="utf-8") as fp:
        fp.write(s.prettify())
